package org.robot.scm.platform.server.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.platform.registry.TelegramRegistry;

@Slf4j
@NoArgsConstructor
public class TgMessageHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/sendTg";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!"GET".equalsIgnoreCase(exchange.getRequestMethod())) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }

        Map<String, String> queryMap = queryToMap(exchange.getRequestURI().getQuery());
        String msg = queryMap.get("msg");
        if (StringUtils.isBlank(msg)) {
            sendFailureResponse(exchange, "发送内容不可为空");
            return;
        }
        CompletableFuture.runAsync(() -> TelegramRegistry.sendToLastChat(msg));
        sendSuccessResponse(exchange, "发送信息成功");
    }
}
